package com.ghsc.ghxc.jsb.app

import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Process
import android.text.TextUtils
import android.util.Log
import android.webkit.WebView
import android.widget.Toast
import com.aliyunsdk.queen.menu.download.BeautyMenuMaterial
import com.blankj.utilcode.util.Utils
import com.cn.appcore.config.AppConfig
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.AUIInteractionLiveManager
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.NimSDKOptionConfig
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.service.MyCustObserveBroadcastMessage
import com.ghsc.ghxc.jsb.service.MyCustObserveCustomNotification
import com.ghsc.ghxc.jsb.service.MyCustRegisterReceiveMessageObserve
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusAnchorLiveAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusAnchorLiveAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusGifAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusGifAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusRedAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusRedAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusRichTextAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusRichTextAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareLiveAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareLiveAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareSourceAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareSourceAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusSysOrderAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusSysOrderAttachmentViewHolder
import com.ghsc.ghxc.jsb.ui.message.activity.MyChatP2PActivity
import com.ghsc.ghxc.jsb.ui.message.activity.MyChatTeamActivity
import com.ghsc.ghxc.jsb.ui.message.view.CustMsgType
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.SDKOptions
import com.netease.nimlib.sdk.msg.MsgServiceObserve
import com.netease.yunxin.kit.chatkit.repo.ChatObserverRepo
import com.netease.yunxin.kit.chatkit.ui.ChatKitClient
import com.netease.yunxin.kit.common.utils.ProcessUtils
import com.netease.yunxin.kit.corekit.im.IMKitClient
import com.netease.yunxin.kit.corekit.im.repo.SettingRepo
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant
import com.netease.yunxin.kit.corekit.route.XKitRouter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.tencent.mmkv.MMKV
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.zj.zjsdk.ZJConfig
import com.zj.zjsdk.ZjSdk
import com.zzhoujay.richtext.RichText
import kotlin.properties.Delegates


/**
 * 类名：App
 * 创建时间 2023/4/6 20:59
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class App: Application() {


    var isInit=false


    override fun onCreate() {
        super.onCreate()
        initApp()
    }
    // SDK预初始化函数

    private fun initApp() {
        instance = this
        AppConfig.init(this)
//        // 设置全局异常处理器
//        Thread.setDefaultUncaughtExceptionHandler( GlobalExceptionHandler(this))
        //工具类初始化
        Utils.init(this)
        initSmartRefresh() //下拉刷新。上拉加载。
        //初始化存储
        MMKV.initialize(this)
        RichText.initCacheDir(this)
        RichText.debugMode = true
        initWebView()
        init()

    }
    private fun getProcessName(context: Context?): String? {
        if (context == null) return null
        val manager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == Process.myPid()) {
                return processInfo.processName
            }
        }
        return null
    }
    private fun initWebView() {
        // WebView多进程处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try {
                val processName = getProcessName(this) ?: getProcessName()
                loge("processName="+processName)
                val packageName = this.packageName
                if (packageName != processName) {
                    WebView.setDataDirectorySuffix(processName)
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
    }
    private fun initSmartRefresh() {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ -> //全局设置主题颜色
            //                layout.setPrimaryColorsId(R.color.main_color, android.R.color.white);
            //                return new BezierCircleHeader(context);
            val header = ClassicsHeader(context)
            header.setAccentColor(
                getCompatColor(R.color.black)
            )

            header.setTextSizeTitle(10f)
            header.setTextSizeTime(10f)
            header.setDrawableSize(12f) //同时设置箭头和图片的大小（dp单位）
            header.setDrawableArrowSize(12f) //设置箭头的大小（dp单位）
            header.setDrawableProgressSize(12f) //设置图片的大小（dp单位）
            header.setArrowResource(R.drawable.icon_refresh)
            header
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //取消内容不满一页时开启上拉加载功能
            layout.setEnableLoadMoreWhenContentNotFull(false)
            layout.setEnableAutoLoadMore(true)  //是否启用列表惯性滑动到底部时自动加载更多
            //                layout.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
            //指定为经典Footer，默认是 BallPulseFooter
            val footer = ClassicsFooter(context)
            footer.setAccentColor(getCompatColor(R.color.black))
            footer.setTextSizeTitle(12f)
            footer.setDrawableSize(14f) //同时设置箭头和图片的大小（dp单位）
            footer.setDrawableArrowSize(14f) //设置箭头的大小（dp单位）
            footer.setDrawableProgressSize(14f) //设置图片的大小（dp单位）
            footer.spinnerStyle = SpinnerStyle.Translate
            footer
        }
    }
    companion object {
        @JvmStatic
        var instance: Context by Delegates.notNull()
            private set
        fun init(){
//            initZhongJian()
//            initYunXinIM()
//            initAliVideo()
            if (!TextUtils.isEmpty(UserManager.getIsFirst())){
                initZhongJian()
                initYunXinIM()
                initAliVideo()
                initYouMeng()

            }
        }

        fun initYouMeng(){
            //设置LOG开关，默认为false
            UMConfigure.setLogEnabled(true)
//            UMConfigure.preInit(instance,CustKey.YM_KEY,"Umeng")
            UMConfigure.init(instance,CustKey.YM_KEY,"Umeng",UMConfigure.DEVICE_TYPE_PHONE,"")
            MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
        }

        //初始化中
        fun  initZhongJian(){
            // 初始化SDK
            // 用户ID，没获取到可以不传
            // 2.4.18版本初始化方式调整，需要使用initWithoutStart方法初始化，并在用户同意隐私协议后调用start方法
            var userid=UserManager.getUserId()
            ZjSdk.initWithoutStart(
                AppConfig.getApplication(),
                ZJConfig.Builder( CustKey.zjAppId)
                    .userId(userid)
                    .build()
            )
            // 2.4.18版本初始化方法调整，需要先调用initWithoutStart方法初始化，并在用户同意隐私协议后调用start方法
            ZjSdk.start(object : ZjSdk.OnStartListener {
                override fun onStartSuccess() {
                    // 需要在start成功后请求广告
                    loge("ZJSDK初始化成功")
                }
                override fun onStartFailed(code: Int, msg: String?) {
                    val text = "ZJSDK初始化失败[$code-$msg]"
//                    if (code == 999001 && msg != null && msg.contains("ignore init on process")) {
//                        // SDK不支持在子进程中初始化，会返回错误
//                        // 可以忽略，不影响主进程上的广告调用
//                        Log.e("ZJSdk", "忽略子进程上的初始化")
//                    } else {
//                        showToast(text)
//                    }
                }
            })
        }
        //网易云信IM
        fun  initYunXinIM(){
            val options: SDKOptions? =
                NimSDKOptionConfig.getSDKOptions(instance,  if (CustKey.APP_EN_MENT==0) CustKey.IM_YUN_XIN_KEY else CustKey.IM_YUN_XIN_KEY_RS)
            IMKitClient.init(instance,null,options!!)
            if (ProcessUtils.isMainProcess(instance)) {
                ChatKitClient.init(instance)
                IMKitClient.toggleNotification(SettingRepo.isPushNotify())
                //监听接受消息

                ChatObserverRepo.registerReceiveMessageObserve(MyCustRegisterReceiveMessageObserve())
                //监听监听自定义系统通知接收回调。
                NIMClient.getService(MsgServiceObserve::class.java)
                    .observeCustomNotification(MyCustObserveCustomNotification(), true)
                //监听监听广播消息收发
                NIMClient.getService(MsgServiceObserve::class.java)
                    .observeBroadcastMessage(MyCustObserveBroadcastMessage(), true)


                //自定义红包
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_RED, CusRedAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_RED, CusRedAttachmentViewHolder::class.java)

                //分享直播间
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_SHARE_LIVE, CusShareLiveAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_SHARE_LIVE, CusShareLiveAttachmentViewHolder::class.java)

                //直播间 主播发红包。发送给粉丝通知
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_LIVE_START, CusAnchorLiveAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_LIVE_START, CusAnchorLiveAttachmentViewHolder::class.java)
//                //app 版本
//                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_APP_VERSION, CusShareVersionAttachment().javaClass)
//                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_APP_VERSION, CusShareVersionAttachmentViewHolder::class.java)
//
                //系统消息 自定义富文本
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_SYSY_RICH_TEXT, CusRichTextAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_SYSY_RICH_TEXT, CusRichTextAttachmentViewHolder::class.java)
//                //系统消息 自定义订单消息
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_SYSY_ORDER, CusSysOrderAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_SYSY_ORDER, CusSysOrderAttachmentViewHolder::class.java)
                //分享素材
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_SHARE_SOURCE, CusShareSourceAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_SHARE_SOURCE, CusShareSourceAttachmentViewHolder::class.java)
                //im 单聊 返送礼物
                ChatKitClient.addCustomAttach(CustMsgType.CUST_IM_CUST_GIF, CusGifAttachment().javaClass)
                ChatKitClient.addCustomViewHolder(CustMsgType.CUST_IM_CUST_GIF, CusGifAttachmentViewHolder::class.java)
            }
            //注册单聊的会话界面
            XKitRouter.registerRouter(RouterConstant.PATH_CHAT_P2P_PAGE, MyChatP2PActivity().javaClass)
            //注册群聊的会话界面
            XKitRouter.registerRouter(RouterConstant.PATH_CHAT_TEAM_PAGE, MyChatTeamActivity().javaClass)



        }

        fun initAliVideo() {
            AUIInteractionLiveManager().setup()
            BeautyMenuMaterial.getInstance().prepare(instance)//提前初始化Beauty ，防止部分贴纸失效
        }
    }
}